/*
 * ResourceReader.java
 *
 * Created on 1 December 2006, 13:27
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.foment.joliage3.core.string;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.foment.joliage3.reports.Report;

/**
 *
 * @author ivan
 */
public class StringIO {
  
  /** Creates a new instance of ResourceReader */
  public StringIO() {
  }
  
  public static String readFromInputStream(InputStream is) throws IOException {
    if (is == null) return "";
    StringBuffer result = new StringBuffer();

    InputStreamReader isr = new InputStreamReader(is, java.nio.charset.Charset.forName("UTF-8"));
    BufferedReader reader = new BufferedReader(isr);

    String line = null;

    while ((line = reader.readLine()) != null) {
      result.append(line);
      result.append(System.getProperty("line.separator"));
    }

    reader.close();

    return result.toString();
  }
  
  public static String readFromResource(String resourceName) throws IOException {
    if (resourceName == null || resourceName.equals("")) return "";
    return readFromInputStream(StringIO.class.getResourceAsStream(resourceName));
  }
  
  public static String readFromFile(String fileName) throws FileNotFoundException, IOException {
    if (fileName == null || fileName.equals("")) return "";
    return readFromInputStream(new java.io.FileInputStream(fileName));
  }
  
  public static String readFromFile(File file) throws IOException {
    if (file == null) return "";
    return readFromInputStream(new java.io.FileInputStream(file));
  }
  
  public static void writeToFile(String fileName, String contents) throws FileNotFoundException, IOException {
    if (fileName == null || fileName.equals("") || contents == null) return;
    writeToOutputStream(new FileOutputStream(fileName), contents);
  }
  
  public static void writeToFile(File file, String contents) throws FileNotFoundException, IOException {
    if (file == null || contents == null) return;
    writeToOutputStream(new FileOutputStream(file), contents);
  }
  
  public static void writeToOutputStream(OutputStream os, String contents) throws IOException {
    if (os == null || contents == null) return;
    OutputStreamWriter osw = new OutputStreamWriter(os, java.nio.charset.Charset.forName("UTF-8"));
    BufferedWriter writer = new BufferedWriter(osw);
    writer.write(contents);
    writer.close();
  }
}
